import React, { useReducer, createContext, useCallback, memo } from 'react';
import { Form, Row, Card, Button } from 'antd';
import { useDeepCompareEffect } from 'react-use';
import { useRequest, defaultFormatResult } from '@/hooks';
import { PageContainer } from '@/molecules';
// import { primaryColor } from '@/defaultSettings';
import { TitleControl, TalentInfoHead } from '@/pages/Recruitment/components';
import { getCandidateInfo } from '@/pages/Recruitment/service';
import { usePositionAndRank } from '@/pages/Recruitment/Hire/hooks';

import {
    Contact,
    OriginalSalary,
    SuggestSalary,
    DiffSalary,
    Result,
    DepartmentSuggest,
    Action,
    HireInfo
} from './containers';

import { COMMUNICATE_RESULT_ENUM } from '../../dictionary';

const styleTitle = title => <div style={{ fontWeight: 'bold', fontSize: 16, paddingLeft: 8 }}>{title}</div>;

const formItemLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 14 }
};

const oneLineLayout = {
    labelCol: { span: 3 },
    wrapperCol: { span: 19 }
};

const generateKey = contacts => {
    const ID_PREFIX = 'contacts-';
    if (!contacts.length) {
        return ID_PREFIX + 0;
    }
    const nextId = Math.max(...contacts.map(item => Number(String(item.key ?? item.id).replace(ID_PREFIX, '')))) + 1;
    return ID_PREFIX + nextId;
};

export const RecorderStateContext = createContext(); // 保存多个录音机录制状态用，用于那个互斥的需求。
const audioReducer = (state, action) => {
    switch (action) {
        case 'start':
            return true;
        case 'stop':
            return false;
        case 'reset':
            return false;
        default:
            return state;
    }
};

/**
 * 检查本条联系记录是否可删除
 */
const checkAllowRemove = (item, index) => {
    if (item.id !== undefined || index === 0) {
        return false;
    }
    return true;
};

const Edit = ({
    form,
    isEdit,
    isDepart,
    isSecond,
    commInfo,
    candidateId,
    employId,
    communicateCode,
    reloadAfterSave
}) => {
    const [isRecording, changeState] = useReducer(audioReducer, false);
    // const recordButtonRef = React.useRef();
    const scrollWrapRef = React.useRef();

    /**
     * 初始化沟通记录
     */
    const getInitArray = useCallback(() => {
        const newArr = [{ key: generateKey([]), recorderRef: React.createRef() }]; // 编辑状态下，需要加一条占位
        if (commInfo?.recruitEmployContactVOList?.length) {
            if (isSecond && commInfo.isSave === 0) {
                return newArr; // 二次谈薪进入，无暂存
            }
            return commInfo.recruitEmployContactVOList;
        }
        if (isEdit) {
            return newArr; // 无暂存, 可编辑状态
        }
        return [];
    }, [commInfo, isSecond]);
    const [recruitEmployContactVOList, setRecruitEmployContactVOList] = React.useState(getInitArray());
    useDeepCompareEffect(() => {
        // 不用useDeepCompareEffect, commInfo 会是不同的空对象
        setRecruitEmployContactVOList(getInitArray());
    }, [commInfo]);

    /**
     *  添加联系记录
     */
    const handleCommunicationRecordAdd = useCallback(() => {
        setRecruitEmployContactVOList([
            ...recruitEmployContactVOList,
            {
                key: generateKey(recruitEmployContactVOList),
                recorderRef: React.createRef()
            }
        ]);
    }, [recruitEmployContactVOList]);

    /**
     *  删除联系记录
     */
    const handleCommunicationRecordRemove = useCallback(
        index => {
            console.log(`删除的index: ${index}`);
            const temp = recruitEmployContactVOList.slice();
            temp.splice(index, 1);
            setRecruitEmployContactVOList(temp);
        },
        [recruitEmployContactVOList]
    );

    // 候选人信息
    const { data: originalTalentInfo = {} } = useRequest(() => getCandidateInfo(candidateId), {
        refreshDeps: [candidateId],
        ...defaultFormatResult
    });

    const {
        positionName,
        positionCode,
        companyAreaCode,
        positionCodeChangeFlag,
        employSalaryCurrencyCode,
        loseDuty, // 岗位失效
        organizationName // 需求部门
    } = usePositionAndRank(employId);

    const talentInfo = {
        ...originalTalentInfo,
        positionName,
        positionCode,
        companyAreaCode,
        employSalaryCurrencyCode,
        loseDuty,
        organizationName
    };

    // 仅为了避免eslint
    const renderItem = (EditComponent, ViewComponent, editFlag = isEdit) => (editFlag ? EditComponent : ViewComponent);

    const commonProps = {
        form,
        commInfo,
        talentInfo,
        oneLineLayout,
        renderItem,
        isEdit,
        isDepart,
        isSecond
    };

    // 判断显示录用信息
    const resultType = isEdit ? form.getFieldValue('resultType') : commInfo?.resultType;
    // 强业务，了解？
    const showHireInfo =
        !isDepart &&
        ![COMMUNICATE_RESULT_ENUM.NEGOTIATE, COMMUNICATE_RESULT_ENUM.PREOUT, COMMUNICATE_RESULT_ENUM.OUT].includes(
            resultType
        );

    return (
        <div style={{ display: 'flex' }} ref={scrollWrapRef}>
            <div style={{ width: '100%' }}>
                <PageContainer>
                    <Row>
                        <TalentInfoHead talent={talentInfo} />
                    </Row>
                    <Form {...formItemLayout}>
                        {/* 神奇的判断展示... */}
                        {!isEdit && (
                            <Card style={{ marginTop: 16 }}>
                                <Result {...commonProps} />
                            </Card>
                        )}
                        {recruitEmployContactVOList.length ? (
                            <TitleControl title="联系记录" titleRender={styleTitle}>
                                {/* 21.08.23 可添加多条联系记录 */}
                                <RecorderStateContext.Provider
                                    value={{
                                        isRecording,
                                        changeState
                                    }}
                                >
                                    {recruitEmployContactVOList.map((item, index) => (
                                        <Contact
                                            key={item.key || item.id}
                                            index={index}
                                            allowRemove={checkAllowRemove(item, index)}
                                            scrollWrapRef={scrollWrapRef}
                                            recordButtonRef={item.recorderRef}
                                            communicateInfo={item}
                                            handleRemove={handleCommunicationRecordRemove}
                                            {...commonProps}
                                        />
                                    ))}
                                </RecorderStateContext.Provider>
                                {isEdit ? (
                                    <Button
                                        type="dashed"
                                        icon="plus"
                                        block
                                        style={{ margin: '10px 0' }}
                                        onClick={handleCommunicationRecordAdd}
                                    >
                                        添加
                                    </Button>
                                ) : null}
                            </TitleControl>
                        ) : null}

                        <TitleControl title="原薪资福利" titleRender={styleTitle} initialActive={!isSecond}>
                            {/* 神奇的判断展示... */}
                            <OriginalSalary {...commonProps} isEdit={isEdit && !isDepart && !isSecond} />
                        </TitleControl>
                        <TitleControl title="建议薪资" titleRender={styleTitle}>
                            <SuggestSalary {...commonProps} employId={employId} />
                        </TitleControl>
                        <TitleControl title="薪资对比" titleRender={styleTitle}>
                            <DiffSalary {...commonProps} />
                        </TitleControl>
                        {isEdit && <Result {...commonProps} />}
                        {showHireInfo && (
                            <TitleControl title="录用信息" titleRender={styleTitle}>
                                <HireInfo {...commonProps} />
                            </TitleControl>
                        )}
                        {/* 2021.6.24 若输入过建议薪资 or 淘汰，则不显示用人单位建议输入组件 */}
                        {isDepart && commInfo?.recruitDeptRecordVO?.suggestedStatus === undefined && (
                            <TitleControl title="用人部门建议" titleRender={styleTitle}>
                                <DepartmentSuggest
                                    communicateCode={communicateCode}
                                    talentInfo={talentInfo}
                                    commInfo={commInfo}
                                    oneLineLayout={oneLineLayout}
                                    candidateId={candidateId}
                                    employId={employId}
                                />
                            </TitleControl>
                        )}
                        {isEdit && !isDepart && (
                            <Action
                                {...commonProps}
                                employId={employId}
                                communicateCode={communicateCode}
                                candidateId={candidateId}
                                recruitEmployContactVOList={recruitEmployContactVOList}
                                positionCodeChangeFlag={positionCodeChangeFlag}
                                reloadAfterSave={reloadAfterSave}
                            />
                        )}
                    </Form>
                </PageContainer>
            </div>
        </div>
    );
};

export default Form.create()(memo(Edit));
